﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using crm_dal.Objects;
using crm_library.Javascript;
using crm_library.Extenstions;

namespace crm_web.DataPages
{
    public partial class CreateSale : System.Web.UI.Page
    {
        crm_dal.Objects.Sale displaySale;
		
		protected void Page_Init(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				ddlClientID.Items.AddRange(Client.GetAll().Select(client => client.ToListItem()).ToArray());
				ddlProductID.Items.AddRange(crm_dal.Objects.Product.GetAll().Select(prod => prod.ToListItem()).ToArray());
				ddlUserID.Items.AddRange(crm_dal.Objects.User.GetAll().Select(usr => usr.ToListItem()).ToArray());
			}

            try
            {
                displaySale = new crm_dal.Objects.Sale(Convert.ToInt32(HttpContext.Current.Session["Selection"]));
				ddlClientID.SelectByValue(displaySale.ClientID);
				ddlUserID.SelectByValue(displaySale.UserID);
                txtDate.Text = displaySale.Date.ToString();
				ddlProductID.SelectByValue(displaySale.ProductID);
			}
			catch (Exception ex)
			{
				Alert.Show(ex.Message, Alert.AlertMessageType.Error);
			}
		}

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            string error = "";
            try
            {
                displaySale.ClientID = Convert.ToInt32(ddlClientID.SelectedValue);
                displaySale.UserID = Convert.ToInt32(ddlUserID.SelectedValue);
                displaySale.Date = Convert.ToDateTime(txtDate.Text);
                displaySale.ProductID = Convert.ToInt32(ddlProductID.SelectedValue);
                //displaySale.Total = Convert.ToDecimal(txtTotal);

                displaySale.Create();
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            if (!String.IsNullOrWhiteSpace(error))
            {
                Alert.Show(error, Alert.AlertMessageType.Error);
            }
            else
            {
                Alert.Show("create succeeded", Alert.AlertMessageType.Message, "/DataPages/Sale.aspx");
            }
        }
    }
}